#!/usr/bin/env python
#coding:utf-8

import os
import sys
import json
import requests
import ftplib
import paramiko
import time
import time
from datetime import datetime
from warnings import filterwarnings
from ftplib import FTP, error_perm


filterwarnings("ignore")


class myFTP_v1(FTP):
    encoding = "utf-8"
    # def __init__(self):
    #     # self.host=None
    #     # self.port = 21
    #     # self.uesr=None
    #     # self.passwd=None
    #     pass

    def DownLoadFile(self, LocalFile, RemoteFile):
        """
        下载指定目录下的指定文件
        """
        bufsize = 1024
        file_handler = open(LocalFile, 'wb')
        # print(file_handler)
        self.retrbinary('RETR ' + RemoteFile, file_handler.write, bufsize)
        file_handler.close()
        print(
            f"download {RemoteFile} to {LocalFile} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )
        return True
    
    def DownLoadFileTree(self, LocalDir, RemoteDir):
        """
        下载整个目录下的文件
        """
        # print("remoteDir:", RemoteDir)
        if not os.path.exists(LocalDir):
            os.makedirs(LocalDir)
        self.cwd(RemoteDir)
        RemoteNames = self.nlst()
        # print("RemoteNames", RemoteNames)
        for idx, remote_file in enumerate(RemoteNames):
            Local = os.path.join(LocalDir, remote_file)
            # print(idx, self.nlst(remote_file))
            full_remote_path = '/'.join((RemoteDir, remote_file))
            if full_remote_path.find(".") == -1:
                if not os.path.exists(Local):
                    os.makedirs(Local)
                self.DownLoadFileTree(Local, full_remote_path)
            else:
                self.DownLoadFile(Local, full_remote_path)
                self.cwd("..")
        return True

    def uploadfile(self, remotepath, localpath):
        """
        从本地上传文件到ftp
        """
        bufsize = 1024
        fp = open(localpath, 'rb')
        self.storbinary('STOR ' + remotepath, fp, bufsize)
        self.set_debuglevel(0)
        fp.close()
        print(
            f"upload {localpath} to {remotepath} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )


class myFtp:
    def __init__(self, host, port=21):
        self.ftp = ftplib.FTP()
        # self.ftp.set_pasv(False)
        self.ftp.connect(host, port)

    def Login(self, user, passwd):
        self.ftp.login(user, passwd)
        # print(self.ftp.welcome)

    def DownLoadFile(self, LocalFile, RemoteFile):
        """
        下载指定目录下的指定文件
        """
        bufsize = 1024
        file_handler = open(LocalFile, 'wb')
        # print(file_handler)
        self.ftp.retrbinary('RETR ' + RemoteFile, file_handler.write, bufsize)
        file_handler.close()
        print(
            f"download {RemoteFile} to {LocalFile} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )
        return True

    def DownLoadFileTree(self, LocalDir, RemoteDir):
        """
        下载整个目录下的文件
        """
        print("remoteDir:", RemoteDir)
        if not os.path.exists(LocalDir):
            os.makedirs(LocalDir)
        self.ftp.cwd(RemoteDir)
        RemoteNames = self.ftp.nlst()
        print("RemoteNames", RemoteNames)
        for file in RemoteNames:
            Local = os.path.join(LocalDir, file)
            print(self.ftp.nlst(file))
            if file.find(".") == -1:
                if not os.path.exists(Local):
                    os.makedirs(Local)
                self.DownLoadFileTree(Local, file)
            else:
                self.DownLoadFile(Local, file)
                self.ftp.cwd("..")
        return True

    def uploadfile(self, remotepath, localpath):
        """
        从本地上传文件到ftp
        """
        bufsize = 1024
        fp = open(localpath, 'rb')
        self.ftp.storbinary('STOR ' + remotepath, fp, bufsize)
        self.ftp.set_debuglevel(0)
        fp.close()
        print(
            f"upload {localpath} to {remotepath} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        )

    def close(self):
        self.ftp.quit()


class mySFTP:
    def __init__(self, host, port=21):
        self.transport = paramiko.Transport((host, port))
        self.transport.banner_timeout = 60
        self.sftp = None

    def Login(self, username, password):
        self.transport.connect(username=username, password=password)
        self.sftp = paramiko.SFTPClient.from_transport(self.transport)

    def sftp_upload(self, local, remote):
        try:
            if os.path.isdir(local):  #判断本地参数是目录还是文件
                for f in os.listdir(local):  #遍历本地目录
                    self.sftp.put(os.path.join(local, f),
                                  os.path.join(remote, f))  #上传目录中的文件
                else:
                    self.sftp.put(local, remote)  #上传文件
        except Exception as e:
            print('upload exception:', e)

    def sftp_download(self, local, remote):
        try:
            if os.path.isdir(local):  #判断本地参数是目录还是文件
                for f in self.sftp.listdir(remote):  #遍历远程目录
                    self.sftp.get(os.path.join(remote, f),
                                  os.path.join(local, f))  #下载目录中文件
                else:
                    self.sftp.get(remote, local)  #下载文件
        except Exception as e:
            print('download exception:', e)

    def sftp_close(self):
        self.sftp.close()
        self.transport.close()


def post_file(base_url, file):

    millis = int(round(time.time() * 1000))
    # print(millis)
    post_url = base_url+str(millis)
    files = {'file': open(file, 'rb')}
    r = requests.post(post_url, files=files)
    state=json.loads(r.text).get('code')
    print(state)
    return state
    


if __name__ == "__main__":

    today = time.strftime('%Y%m%d', time.localtime(time.time()))
    ip = 'ftp.ptree.jaxa.jp'  # ftp://47.96.184.134
    username = 'davidt2013_163.com'
    password = 'SP+wari8'
    # filename = 'test.txt'
    # src_file = os.path.join("upload_file", filename)

    ftp_obj = myFtp(ip)
    ftp_obj.Login(username, password)
    # ftp_obj.uploadfile("/data/test_upload_new.txt", src_file)
    ftp_obj.DownLoadFile("a.csv", "/pub/himawari/L3/WLF/010/202309/01/H09_20230901_0000_L3WLF010_FLDK.06001_06001.csv",
                         )
    ftp_obj.close()

    # sftp_obj=mySFTP(ip)
    # sftp_obj.Login(username, password)
    # sftp_obj.sftp_upload(src_file, "/data/test_upload_sftp.txt", )
    # sftp_obj.sftp_close()

    # url = 'http://fireproxy.answer12.com/api/blade-monitor/fire-point/add?currentTimeMillis='
    # file2post = 'post_file\\fwi_230424.geojson'

    """v1
        host = '47.96.184.134'  # ftp://47.96.184.134
    port = 21
    username = 'star-get'
    password = 'starvision'
    filename = 'test.txt'
    data_dir = '/data'

    # print(time.time())
    # print(datetime.now().strftime("%Y%m%d"))  # "%Y-%m-%d %H:%M:%S"

    ftpServer = myFTP()
    ftpServer.connect(host=host, port=port)
    ftpServer.login(user=username, passwd=password)
    
    # local_file = "test.csv"
    # remote_file = "/".join((data_dir, "hotposi_H8_20230423_0730_zhej_merged_geo.csv"))
    # print(remote_file)
    # ftpServer.DownLoadFile(local_file, remote_file)

    ftpServer.DownLoadFileTree("batch_download", data_dir)
    """

